package com.yanqu.road.server.cmd.activity.xingyoushanshui;

import com.yanqu.road.entity.activity.youxing.config.XingYouConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.XingYouShanShuiProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.CmdApi;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.shanshui.XingYouShanShuiMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;

@CmdApi(reqMsg = XingYouShanShuiProto.ShanShuiUseItemReq.class, respMsg = XingYouShanShuiProto.ShanShuiUseItemRsp.class)
@Cmd(code = Protocol.S_XING_YOU_SHAN_SHUI_USE_ITEM, desc = "使用活动道具(建筑)")
public class ShanShuiUseItemCmd extends AbstractCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        XingYouConfig config = XingYouShanShuiMgr.getConfig();
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            ret = GameErrorCode.E_ACTIVITY_NO_FOUND;
            return;
        }
        XingYouShanShuiProto.ShanShuiUseItemReq req = XingYouShanShuiProto.ShanShuiUseItemReq.parseFrom(packet.getBytes());
        if(req.hasUserProp()){
            int itemId = req.getUserProp();
            int num = 1;
            if(req.hasUserPropNum()){
                num = req.getUserPropNum();
            }
            if(num <= 0){
                ret = GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
                return;
            }
            if(itemId != config.getSHANSHUI_RED_ENVELOPE_ID() && itemId != config.getSHANSHUI_EXPANSION_PLAN_ID()){
                ret = GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
                return;
            }
            Property property = new Property();
            property.addProperty(itemId, num);
            if(!player.getModule(CurrencyModule.class).currencyIsEnough(property)){
                ret = GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                return;
            }
            player.getModule(PreReduceModule.class).preReduce(property);
        }
        player.sendUnionActivityGroupPacket(Protocol.C_XING_YOU_SHAN_SHUI_USE_ITEM, req.toBuilder(), config.getActivityInfo().getActivityId());
    }

    @Override
    public void sendData(GamePlayer player) {
        if(ret != 0){
            player.sendPacket(Protocol.U_XING_YOU_SHAN_SHUI_USE_ITEM, XingYouShanShuiProto.ShanShuiUseItemRsp.newBuilder().setRet(ret));
        }
    }
}
